package com.gemframework.common.util;


import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * ClassName: ApiBaseController
 * Description:
 * date: 2020/1/24 9:23
 *
 * @author afeng
 * @since JDK 1.8
 */
public class BaseApiController {

    @Autowired
    public HttpServletRequest request;

    @Autowired
    public HttpServletResponse response;


    /**
     * 获取键值对参数
     */
    public String getParameter(String key) {
        return request.getParameter(key);
    }

    /**
     * 获取流参数，如json、xml
     */
    public String getBufferParam() {
        String param = null;
        try (BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            if (sb.length() < 1) {
                return "";
            }
            param = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param;
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {

    }


    /**
     * 返回成功消息
     */
    public ApiResult success(Object data) {
        return ApiResult.success(data);
    }

    public ApiResult success(String msg, Object data) {
        return ApiResult.success(msg, data);
    }

    public ApiResult success() {
        return ApiResult.success();
    }


    /**
     * 返回失败消息
     */
    public ApiResult error() {
        return ApiResult.error();
    }

    public ApiResult error(String message) {
        return ApiResult.error(message);
    }

    public ApiResult error(ApiResult.Type type, String message) {
        return new ApiResult(type, message);
    }

    /**
     * 返回失败消息
     */
    public ApiResult fail() {
        return ApiResult.fail();
    }

    public ApiResult fail(String message) {
        return ApiResult.fail(message);
    }

    public ApiResult fail(ApiResult.Type type, String message) {
        return new ApiResult(type, message);
    }

    public ApiResult fail(Object data) {
        return ApiResult.fail(data);
    }


}
